package ru.alt22.visor.php.core.codegen;

import java.util.ArrayList;

import org.eclipse.php.internal.core.phpModel.phpElementData.PHPModifier;

public class PHPMethod {
	
	private int modifiers;
	private String name;
	private ArrayList<PHPParameter> parameters;
	private String body;
	
	public PHPMethod(int modifiers, String name) {
		this(modifiers, name, null);
	}
	
	public PHPMethod(int modifiers, String name, String body) {
		setModifiers(modifiers);
		setName(name);
		setBody(body);
		parameters = new ArrayList<PHPParameter>();
	}

	public void setModifiers(int modifiers) {
		this.modifiers = modifiers;
	}

	public int getModifiers() {
		return modifiers;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}
	
	public void addParameter(String name, String type, String defaultValue) {
		parameters.add(new PHPParameter(name, type, defaultValue));
	}
	
	public ArrayList<PHPParameter> getParameters() {
		return parameters;
	}

	public void setBody(String body) {
		this.body = body;
	}

	public String getBody() {
		return body;
	}

	public String toString() {
		return toString(1);
	}

	public String toString(int indent) {
		return toString(indent, true);
	}

	public String toString(int indent, boolean withBody) {
		StringBuffer result = new StringBuffer();

		result.append(indent(indent));
		result.append(PHPModifier.toString(this.getModifiers()));
		if (this.getModifiers() > 0) {
			result.append(" ");
		}
		result.append("function ");
		result.append(this.getName());
		
		result.append("(");
		for (int i = 0; i < getParameters().size(); i++) {
			PHPParameter parameter = (PHPParameter) getParameters().get(i);
			result.append(parameter.toString());
			if (i != getParameters().size() - 1) {
				result.append(", ");
			}
		}
		result.append(")");
		
		if (PHPModifier.isAbstract(this.getModifiers()) || !withBody) {
			result.append(";\n");
		} else {
			result.append(" {\n");
			if (getBody() != null && getBody().length() > 0) {
				String[] lines = getBody().split("\n");
				for (int i = 0; i < lines.length; i++) {
					result.append(indent(indent + 1));
					result.append(lines[i]);
					result.append("\n");
				}
			}
			result.append(indent(indent));
			result.append("}\n");
		}
		return result.toString();
	}
	
	private String indent(int indent) {
		String result = new String("");
		for (int i = 0; i < indent; i++) {
			result += "\t";
		}
		return result;
	}

}
